package Server;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 *X
 */
//displayserver.DisplayServer.java
import Server.GUI.DBServer;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.*;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageObserver;
import java.awt.image.ReplicateScaleFilter;
import java.awt.image.BufferedImage;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DisplayServer extends Thread {

    ServerSocket ss = null;
    ServerSocket admin = null;
    Vector<ClientThread> clientList = new Vector<ClientThread>();
    long sleepInterval = 10000;

    public DisplayServer(long interval) throws Exception {
        ss = new ServerSocket(20020);
        admin = new ServerSocket(20021);
        sleepInterval = interval;
        this.setPriority(MIN_PRIORITY);
        this.start();
        startServer();
        
    }

    private void startServer() {
        Socket client = null;
       
     // System.err.println("Starts listening for clients");
        ClientThread ct = null;
        while (true) {
            try {
                client = ss.accept();
                ct = new ClientThread(client);
                clientList.addElement(ct);
                ct.start();
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public void run() {
     String localHost=  "127.0.0.1";
       // String localHost = "192.168.1.2";
        try {
            JOptionPane.showMessageDialog(null, "Ban hay nhan ok de bat dau qua trinh ket noi!!!")  ;
            System.out.println("Client from connected22222");
            localHost = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception ex) {
        }
        while (true) {
            try {
                System.out.println("Client from connected");
                Socket ad = admin.accept();

                if (ad.getInetAddress().getHostAddress().equals(localHost)
                        && ad.getInputStream().read() == 'X') {
                    ss.close();
 
                    
                   // Socket ss=s.accept(); //synchronous
				
			
				
				//System.out.println("Talking to client");
				//System.out.println(ss.getPort());
				
				
                                      for (int i = 0, n = clientList.size(); i < n; i++) {
                        clientList.get(i).client.close();
                    }
                    System.exit(0);
                    
                    
                 // Socket ak ;   
                //    Socket ss;
                   // InputStream a= ss.getInputStream();
               // BufferedReader br=new BufferedReader(new InputStreamReader(a));
               // String receivedMessage;
                //receivedMessage= br.readLine();
                  //  System.out.println("Client from" +receivedMessage+"connected");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private void removeMe(Socket s) {
        clientList.removeElement(s);
    }

    
      private static String getTagValue(String sTag, Element eElement) {
	NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
 
        Node nValue = (Node) nlList.item(0);
 
	return nValue.getNodeValue();
        
    }
    
    
    class ClientThread extends Thread {

        Socket client = null;
        ObjectOutputStream os = null;
        InputStream is = null;

        public ClientThread(Socket s) {
            client = s;
            int kiemtra=0;
            String k="";
            try {
                System.out.println("Client from connected");
                os = new ObjectOutputStream(s.getOutputStream());
                is = s.getInputStream();
                 OutputStream osi=s.getOutputStream();
                System.out.println("Client from " + s.getInetAddress().getHostAddress() + " connected");
                BufferedReader br=new BufferedReader(new InputStreamReader(is));
                String receivedMessage;
                
               // OutputStream os=ss.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                
                File  fXmlFile = new File("Data.xml");
               
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(fXmlFile);
		doc.getDocumentElement().normalize();
                
		System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
		NodeList nList = doc.getElementsByTagName("User");
		System.out.println("-----------------------");
                 int dong=0; 
                 receivedMessage=br.readLine();
                   String receivedMessage1= receivedMessage;
                   System.out.println("Received : " + receivedMessage1);
                         receivedMessage=br.readLine();
			System.out.println("Received : " + receivedMessage); 
		for (int temp = 0; temp < nList.getLength(); temp++) {
                       
		   Node nNode = nList.item(temp);
		   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
		      Element eElement = (Element) nNode;
                            // tfduongdan.setText();
                      

                       System.out.println("Received : "+ getTagValue("Name", eElement) );
                       System.out.println("Received : "+ nList.getLength( )+"sdfdsfds");
			
                        
		      //System.out.println(getTagValue("MSSV", eElement));
                       if (getTagValue("Name", eElement).compareTo(receivedMessage1)==0&&getTagValue("Pass", eElement).compareTo(receivedMessage)==0)
                       {
                            
                           
                          // DataInputStream din=new DataInputStream(System.in);
						kiemtra =1;
                       }
                  }
                }
                

		     // System.out.println("Ten : " + getTagValue("Ten", eElement));
                      // receivedMessage=getTagValue("Ten", eElement);
	             // System.out.println("NgaySinh : " + getTagValue("NgaySinh", eElement));
                     //  mang[dong][2]= getTagValue("NgaySinh", eElement);
		      //System.out.println("GioiTinh : " + getTagValue("GioiTinh", eElement));
                      // mang[dong][3]= getTagValue("GioiTinh", eElement);
                      // dong++;
                      
                     if (kiemtra==0)
                       {
                       // k= "thatbai";
                k="0";
                   	bw.write(k);
			bw.newLine();
			bw.flush(); 
                        System.out.println("Received :dfdgdfgdf "+k); 
                           //s.close(); 
                          // client.close();
                          // ss.close();
                          // this.closeAll();
                       }
                       else 
                      {
                           //DataInputStream din=new DataInputStream(System.in);
                       
			k="1";
			bw.write(k);
			bw.newLine();
			bw.flush();
                         DBServer.main(null);

            //dispose();
                       }
                      // System.out.println("Received : " + getTagValue("Name", eElement)); 
                
   
                
                
                
                
                //InputStream is=s.getInputStream();
				
                             // do
                                  // for(int i=0;i<2;i++)
			
				{
					
					//if (receivedMessage.equalsIgnoreCase("quit"))
					{
						//System.out.println("Client has left !");
						//break;
					}
					//else
					{
						//DataInputStream din=new DataInputStream(System.in);
						//String k=din.readLine();
						//bw.write(k);
						//bw.newLine();
						//bw.flush();
					}
				}
				//while (true);
                   // br.close();
                // os = new ObjectOutputStream(s.getOutputStream());
              // is = s.getInputStream();              
               // os = new ObjectOutputStream(s.getOutputStream());
               // is = s.getInputStream();
                
                //System.out.println("Client from " + s.toString() + " connected");
             //   Socket ss=s.accept(); //synchronous
				
			
				
			//	System.out.println("Talking to client");
				//System.out.println(ss.getPort());
				
		//InputStream is=ss.getInputStream();
                //BufferedReader br=new BufferedReader(new InputStreamReader(is));
                
                
                
            } catch (Exception ex) {
                ex.printStackTrace();
                
                
                
            }
        }

  
        
        public void run() {
            
          /*  java.awt.image.BufferedImage img = null;
            Robot r = null;
            try {
                r = new Robot();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            
   // ImageFilter imf = new ReplicateScaleFilter(w, h);
  // FilteredImageSource fis = new FilteredImageSource(src.getSource(), imf);
  // ImageFilter imf = new ReplicateScaleFilter(w, h);
   
            Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle rect = new Rectangle(0, 0, size.width, size.height);
           //rect.setSize(300 * size.width / size.height, 300);
            javax.swing.ImageIcon icon = null;
            
            while (true) {
                try {
                    System.gc();
                    img = r.createScreenCapture(rect);
                    
                   // int newImageWidth = imageWidth * zoomLevel;
//int newImageHeight = imageHeight * zoomLevel;


                    
                    
       // double scale = 0.5;  // 50 %
      //double w = icon.getIconWidth()*scale ;
     // double h = icon.getIconHeight() * scale;
         
BufferedImage resizedImage = new BufferedImage(size.width,size.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(img,0,0, size.width, size.height, null);
g.dispose();
System.out.println("Client has left !");
              icon = new javax.swing.ImageIcon(resizedImage);
                   os.writeObject(icon);
                    os.flush();
                   
                    icon = null;
                    System.gc();
                    img = null;
                    //System.err.println("aaaaaaa");
                    //try {
                      //  Thread.currentThread().sleep(50);
                  //  } catch (Exception e) {
                   // }
                } catch (Exception ex) {
                    closeAll();
                   // break;
                }
//closeAll();
            }
*/
        }

        private void closeAll() {
            DisplayServer.this.removeMe(client);
            try {
                os.close();
                is.close();
                client.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String arg[]) throws Exception {
        long interval = 1;
       // if (arg.length == 1) {
         //   interval = Long.parseLong(arg[0]);
       // }
        new DisplayServer(interval);
    }
}